//################################
// 版权所有：鸽子游戏俱乐部
// 系统名称：鸽子游戏俱乐部-移动版
// 文件名称：main.js
// 创建时间：2017年04月08日
// 创建人员：Lemo
// 功能说明：app tab导航框架
//################################

'use strict';

import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    ScrollView,
    Alert,
    TouchableOpacity,
    Image,
    Dimensions,
    NativeModules,
    AppState,
    Linking,
    InteractionManager,
} from 'react-native';

import Images from '../../images';
import {
    Colors,
    UIConstants,
    FontSizes,
    PubSubTopics,
    Routes,
    CommonData,
} from '../../common';

import ScrollableTabView from 'react-native-scrollable-tab-view';
import Orientation from 'react-native-orientation';
import Drawer from 'react-native-drawer';

import {clearLogin, logout,clearActionType} from '../../actions';

import MainTabBar from './mainTabBar';
import LogoutModal from './logoutModal';

import DrawerContentContainer from '../containers/drawerContentContainer';

import FirstPageContainer from '../../firstpage/containers/firstPageContainer';
import IncrementsContainer from '../../increments/containers/incrementsContainer';
import MyContainer from '../../my/containers/myContainer';
import LoginContainer from '../../login/containers/loginContainer';
import SplashContainer from '../../login/containers/splashContainer';
import MyResetPwdContainer from '../../my/containers/myResetPwdContainer';

import * as ActionTypes from '../../actions/types';

// import { hardwareBackPress, exitApp } from 'react-native-back-android';
import { hardwareBackPress, exitApp } from '../../components/pandaBackAndroid';

import PubSub from 'pubsub-js';

import ConfirmDialog from '../../components/dialog';

const BACKGROUND_WAIT_TIMEOUT = 600000;
const PWD_EXPIRED_TIME = 3600 * 24 * 7 * 1000;

class Main extends Component {
    constructor(props) {
        super(props);

        this.onChangeTab=this.onChangeTabFunc.bind(this);

        this.currentTab=UIConstants.main.first_page;

        this.isDrawerOpen = false;
        this.toggleDrawer = this.toggleDrawerFunc.bind(this);

        this.state = {
            title: '',
            content: '',
            confirmLabel: '',
            cancelLabel: '',
            confirmFunc: () => null,
            cancelFunc: () => null,
            dialogType: '',
            iconType: '',
        };
    }

    componentDidMount() {
        this.onHardwareBackPressedEvent = PubSub.subscribe(PubSubTopics.HARDWARE_BACK_PRESSED, () => {this.onHardwareBackPressedHandler()});
        this.onLogoutModalOpenEvent = PubSub.subscribe(PubSubTopics.MY_OPEN_LOGOUT_MODAL, () => {this.onLogoutModalOpenHandler()});
        this.onDidFocusEvent = PubSub.subscribe(PubSubTopics.MAIN_ONDIDFOCUS, () => {this.onDidFocusHandler()});
        
        this.onConfirmDialogOpenEvent = PubSub.subscribe(PubSubTopics.CONFIRM_DIALOG_OPEN, (event, params) => {this.onConfirmDialogOpenHandler(params)});

        this.closeDrawerEvent = PubSub.subscribe(PubSubTopics.GEZI_CLOSE_DRAWER, () => {this.drawer.close()});

        AppState.addEventListener('change', () => {this.handleAppStateChange()});

        this.checkPwdExpired();
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this.onHardwareBackPressedEvent);
        PubSub.unsubscribe(this.onLogoutModalOpenEvent);
        PubSub.unsubscribe(this.onDidFocusEvent);

        PubSub.unsubscribe(this.onConfirmDialogOpenEvent);
        
        PubSub.unsubscribe(this.closeDrawerEvent);

        AppState.removeEventListener('change', this.handleAppStateChange);
    }

    checkPwdExpired() {
        let now = new Date();
        // now.setHours(23, 59, 59, 999);

        if (CommonData.pwdExpireTime && (CommonData.pwdExpireTime - now.getTime()) < PWD_EXPIRED_TIME) {
            // 提示用户密码即将过期
            let days = (CommonData.pwdExpireTime - now.getTime()) / (3600 * 24 * 1000);
            days = Math.floor(days);
            CommonData.pwdExpireRemainDays = days;

            if (this.confirmDialog) {
                this.setState({
                    title: UIConstants.my.kindlyPrompt,
                    content: UIConstants.my.pwdExpiredMsg.replace('{DAYS}', days),
                    confirmLabel: UIConstants.my.pwdExpiredConfirmLabel,
                    cancelLabel: UIConstants.my.pwdExpiredCancelLabel,
                    confirmFunc: () => {this.goToResetPwdPage()},
                    cancelFunc: () => {this.resetPwdLater()},
                    dialogType: 'all',
                    iconType: 'none',
                });

                this.confirmDialog.open();
            }
        }
    }

    goToResetPwdPage() {
        const {navigatorRoot} = this.props;
        InteractionManager.runAfterInteractions(()=>{
            navigatorRoot.push({
                name: Routes.MY_RESETPWD,
                component: MyResetPwdContainer,
                friend: true,
            });
        });
    }

    resetPwdLater() {
        PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, UIConstants.my.resetPwdLaterTips);
    }

    onConfirmDialogOpenHandler(params) {
        if (this.confirmDialog) {
            this.setState({
                title: params.title,
                content: params.content,
                confirmLabel: params.confirmLabel,
                cancelLabel: params.cancelLabel,
                confirmFunc: params.confirmCallback,
                cancelFunc: params.cancelCallback,
                dialogType: params.dialogType,
                iconType: params.iconType,
            });

            this.confirmDialog.open();
        }
    }

    handleAppStateChange() {
        if (AppState.currentState === 'active') {
            console.log('active');
            this.date2 = new Date();
            let interval = this.date2.getTime() - this.date1.getTime();
            console.log('interval--->' + interval);
            if (interval >= BACKGROUND_WAIT_TIMEOUT) {
                CommonData.isAppInitAfterLogin=true;
                const { dispatch, navigatorRoot } = this.props;
                // 清理login state树
                dispatch(clearActionType());
                navigatorRoot.resetTo({
                    name: Routes.SPLASH,
                    component: SplashContainer,
                });
            }
        }
        else if (AppState.currentState === 'background') {
            console.log('background');
            this.date1 = new Date();
        }
        else if (AppState.currentState === 'inactive') {
            console.log('inactive');
        }
    }
    
    onHardwareBackPressedHandler() {
        if (CommonData.isAnyModalOpen) {
            PubSub.publish(PubSubTopics.ALL_MODAL_CLOSE);
            return;
        }

        let navigatorRouteStack=this.contactsNavigator?this.contactsNavigator.getRouteStack():[];
        if(this.currentTab===UIConstants.main.contacts&&navigatorRouteStack.length>1 && CommonData.currentRoute.name !== Routes.EMAIL_EDITOR){
            this.contactsNavigator.backPress();
            return true;
        }
        
        switch (CommonData.currentRoute.name) {
            case Routes.EMAIL_NAVIGATOR:
                this.jumpToRoute(Routes.MAIN,this.props.navigatorLevel1);
                break;
            case Routes.EMAIL:
                this.jumpToRoute(Routes.MAIN,this.props.navigatorLevel1);
                break;
            case Routes.MAIN_NAVIGATOR:
                this.confirmExit();
                break;
            case Routes.MAIN:
                this.confirmExit();
                break;
			case Routes.ASMP_PERFORMANCE_LANDSCAPE_CHART:
                setTimeout(() => { Orientation.lockToPortrait(); }, 100);
                CommonData.currentNavigator.pop();
                break;
            default:
                CommonData.currentNavigator.pop();
                //CommonData.currentRoute.pop();
                break;
        }
    }

    onLogoutModalOpenHandler() {
        this.logoutModal && this.logoutModal.openModal();
    }

    onDidFocusHandler() {
        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);
    }
    

    handleHardwareBackPress() {
        PubSub.publish(PubSubTopics.HARDWARE_BACK_PRESSED);

        return true;
    }

    jumpToRoute(routeName,navigator) {
        // PubSub.publish(PubSubTopics.SPINKIT_MODAL_OPEN, UIConstants.main.jumpToMain);

        // setTimeout(() => {
            let routes = navigator.getCurrentRoutes();
            for (let i = 0;i < routes.length;i++) {
                if (routes[i].name === routeName) {
                    navigator.jumpTo(routes[i]);
                    break;
                }
            }
        // }, 1000);
    }

    popToPrev() {
        const { navigator } = this.props;
        navigator.pop();
    }

    confirmExit() {
        Alert.alert('提示', '确认退出移动办公?', [{text: UIConstants.login.alert_confirm, onPress: () => {this.props.dispatch(clearLogin());}}, {text: UIConstants.login.alert_cancel, onPress: () => console.log('cancel')},]);
    }

    onMenuPressed(menuName) {
        switch (menuName) {
            case UIConstants.my.signout:
                PubSub.publish(PubSubTopics.SPINKIT_MODAL_OPEN, UIConstants.logout.logoutTips);
                CommonData.isAppInitAfterLogin=true;
                setTimeout(() => {
                    const { dispatch } = this.props;
                    dispatch(logout());
                }, 300);
                break;
            case UIConstants.my.closeapp:
                CommonData.isAppInitAfterLogin=true;
                NativeModules.PandaNativeModule.exitApp();
                break;
            case UIConstants.my.cancel:
                break;
            default:
                break;
        }
    }

    componentWillReceiveProps(nextProps) {
        const { dispatch } = this.props;
        switch (nextProps.actionType) {
            case ActionTypes.LOGOUT_SUCCESS:
            case ActionTypes.LOGOUT_FAILED:
                //navigator to login page
                this.logoutSuccess();
                dispatch(clearActionType());
                break;
            case ActionTypes.LOGIN_LOGINWITHUSERNAMEPASSWORD_CLEAR:
                CommonData.isAppInitAfterLogin=true;
                NativeModules.PandaNativeModule.exitApp();
                break;
            default:
                break;
        }
    }

    logoutSuccess() {
        PubSub.publish(PubSubTopics.SPINKIT_MODAL_CLOSE);
        CommonData.isAppInitAfterLogin=true;
        const { dispatch, navigatorRoot } = this.props;
        
        // 清理login state树
        dispatch(clearLogin());
        navigatorRoot.resetTo({
            name: Routes.LOGIN,
            component: LoginContainer,
            isLogout: true,
        });
    }
    onMakeACall(menuName){
        return Linking.openURL('tel:'+menuName)
    }
    onChangeTabFunc(event) {
        this.currentTab = event.ref.props.tabLabel;
    }

    toggleDrawerFunc() {
        this.isDrawerOpen ? this.drawer.close() : this.drawer.open();
    }

    _drawOpen() {
        this.isDrawerOpen = true;
    }

    _drawClose() {
        this.isDrawerOpen = false;
    }

    render() {
        return (
            <View style={styles.container}>
                <Drawer
                    ref={(ref) => {this.drawer = ref}}
                    type={'displace'}
                    side={'left'}
                    tapToClose={true}
                    content={
                        <DrawerContentContainer {...this.props}/>
                    }
                    styles={{main: {shadowColor: '#000000', shadowOpacity: 0.3, shadowRadius: 15}}}
                    onOpen={() => {
                        this._drawOpen();
                    }}
                    onClose={() => {
                        this._drawClose();
                    }}
                    captureGestures={true}
                    acceptDoubleTap={true}
                    acceptPan={false}
                    panThreshold={0.08}
                    panOpenMask={0.0}
                    openDrawerOffset={0.3}
                    closedDrawerOffset={0}
                    negotiatePan={true}
                    tweenDuration={300}
                    tweenHandler={(ratio) => ({
                        mainOverlay: { backgroundColor : 'black', opacity: 0.1 * ratio }
                    })}
                >
                    <View style={styles.header}>
                        <TouchableOpacity style={styles.headericonview} onPress={this.toggleDrawer}>
                            <Image source={Images.DrawerMenu} style={styles.headericon} resizeMode={Image.resizeMode.contain} />
                        </TouchableOpacity>
                        <Text style={styles.headertext}>
                            {UIConstants.firstPage.app_name}
                        </Text>
                        <TouchableOpacity style={styles.headericonview} disable={true}>
                            <Image source={Images.DrawerMenu} style={[styles.headericon,{opacity:0}]} resizeMode={Image.resizeMode.contain} />
                        </TouchableOpacity>
                    </View>
                    <ScrollableTabView
                        tabBarPosition={'bottom'}
                        initialPage={0}
                        locked={true}
                        renderTabBar={() => <MainTabBar />}
                        onChangeTab={this.onChangeTab}
                        >
                        <ScrollView tabLabel={UIConstants.main.rent_game} style={styles.tabview}>
                            <FirstPageContainer {...this.props} />
                        </ScrollView>
                        <ScrollView tabLabel={UIConstants.main.others} style={styles.tabview}>
                            <IncrementsContainer {...this.props} />
                        </ScrollView>
                        <ScrollView tabLabel={UIConstants.main.my} style={styles.tabview}>
                            <MyContainer {...this.props} />
                        </ScrollView>
                    </ScrollableTabView>
                </Drawer>

                <LogoutModal ref={(ref) => {this.logoutModal = ref}} onMenuPress={(menuName) => {this.onMenuPressed(menuName)}} />
                
                <ConfirmDialog
                    ref={(ref) => {this.confirmDialog = ref}}
                    title={this.state.title}
                    content={this.state.content}
                    confirmLabel={this.state.confirmLabel}
                    cancelLabel={this.state.cancelLabel}
                    confirmCallback={this.state.confirmFunc}
                    cancelCallback={this.state.cancelFunc}
                    type={this.state.dialogType}
                    iconType={this.state.iconType}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        height: Dimensions.get('window').height,
    },
    header: {
        height: 60,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: Colors.appHeaderBackground,
    },
    headericonview: {
        flexDirection: 'row',
        padding: 10,
        marginBottom: -10,
        marginLeft: 5,
        alignItems: 'center',
    },
    headericon: {
        width: 26,
        height: 26,
    },
    headertext: {
        flex: 1,
        fontSize: FontSizes.firstPageHeader,
        color: Colors.appHeaderText,
        textAlign: 'center',
        alignSelf: 'center',
        marginBottom: -12,
    },
    tabView: {
        flex: 1,
        padding: 10,
    },
    card: {
        borderWidth: 1,
        backgroundColor: '#fff',
        borderColor: 'rgba(0,0,0,0.1)',
        margin: 5,
        flex: 1,
        padding: 15,
        shadowColor: '#ccc',
        shadowOffset: { width: 2, height: 2, },
        shadowOpacity: 0.5,
        shadowRadius: 3,
    },
});

const EnhancedMain = hardwareBackPress(Main);

export default EnhancedMain;